//
//  API_Codable_Demo2VC.swift
//  APSwift
//
//  Created by jianbo.pei on 2024/8/21.
//

import UIKit

class API_Codable_Demo2VC: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        test1()
    }


}

/**
自定义键名有多个，比如 `var name: String`，
不论后台`json`返回的是`nickname` 还是`name`, 都能处理。
 */
extension API_Codable_Demo2VC {
    struct Person: Codable {
        var name: String
        var age: Int
        var isEmployed: Bool

        enum CodingKeys: String, CodingKey {
            case name
            case nickname
            case age
            case isEmployed = "is_employed"
        }
        
        // 自定义解码
        init(from decoder: Decoder) throws {
            let container = try decoder.container(keyedBy: CodingKeys.self)
            
            // 尝试解码 `name` 或 `nickname`
            if let nameValue = try? container.decode(String.self, forKey: .name) {
                name = nameValue
            } else if let nicknameValue = try? container.decode(String.self, forKey: .nickname) {
                name = nicknameValue
            } else {
                throw DecodingError.keyNotFound(CodingKeys.name, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Neither 'name' nor 'nickname' key found"))
            }
            
            age = try container.decode(Int.self, forKey: .age)
            isEmployed = try container.decode(Bool.self, forKey: .isEmployed)
        }
        
        // 自定义编码
        func encode(to encoder: Encoder) throws {
            var container = encoder.container(keyedBy: CodingKeys.self)
            try container.encode(name, forKey: .name)
            try container.encode(age, forKey: .age)
            try container.encode(isEmployed, forKey: .isEmployed)
        }
    }
    
    private func test1() {
        let jsonString1 = """
        {
            "name1": "Alice",
            "age": 28,
            "is_employed": true
        }
        """

        let jsonString2 = """
        {
            "nickname1": "Ally",
            "age": 28,
            "is_employed": true
        }
        """

        if let jsonData1 = jsonString1.data(using: .utf8),
           let jsonData2 = jsonString2.data(using: .utf8) {
            do {
                let person1 = try JSONDecoder().decode(Person.self, from: jsonData1)
                print("Person 1: \(person1)")

                let person2 = try JSONDecoder().decode(Person.self, from: jsonData2)
                print("Person 2: \(person2)")
            } catch {
                print("Failed to decode: \(error)")
            }
        }
    }
}
